package com.deepglint.transform;

import com.deepglint.beans.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.io.InputStream;

/**
 * @author mj
 * @version 1.0
 * @date 2021-11-15 21:04
 */
public class TransformTest_RollingAggregation {
    public static void main(String[] args) throws Exception{
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        String inputPath = "C:\\Users\\马军\\Desktop\\Idea-workspace\\flink\\src\\main\\resources\\source.txt";
        DataStream<String> inputStream = env.readTextFile(inputPath);

        // 转换成SensorReading类型
        DataStream<SensorReading> streamMap = inputStream.map((MapFunction<String, SensorReading>) value -> {
            String[] split = value.split(",");
            return new SensorReading(split[0], split[1], new Long(split[2]), new Double(split[3]));
        });

        // 分组(根据字段值分组，填写的是字段名)
        KeyedStream<SensorReading, Tuple> keyBy = streamMap.keyBy("id");
        // 根据字段的值
//        KeyedStream<SensorReading, String> keyBy1 = streamMap.keyBy(SensorReading::getId);

        // 滚动聚合，去当前的最大值(只会更新一个temperature字段)
        DataStream<SensorReading> resultStream = keyBy.max("temperature");
        // 滚动聚合，去当前的最大值(全部字段更新)
//        DataStream<SensorReading> resultStream = keyBy.maxBy("temperature");

        resultStream.print();

        env.execute();
    }
}
